package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateTimeZoneConverter;
import com.zzyl.nursing.dto.DeviceDetailVo;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDataVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 设备Service业务层处理
 *
 * @author ruoyi
 * @date 2025-10-17
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private IoTDAClient client;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    /**
     * 查询设备列表
     *
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 从物联网平台同步产品列表
     */
    @Override
    public void syncProductList() {
        //请求参数
        ListProductsRequest listProductsRequest = new ListProductsRequest();
        //设置条数
        listProductsRequest.setLimit(50);
        //发起请求
        ListProductsResponse response = client.listProducts(listProductsRequest);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("同步失败");
        }
        //存储到redis
        List<ProductSummary> products = response.getProducts();
        stringRedisTemplate.boundValueOps(CacheConstants.IOT_ALL_PRODUCT_LIST).set(JSONUtil.toJsonStr(products));
    }

    /**
     * 查询所有产品列表
     */

    @Override
    public List<ProductVo> allProduct() {
        //从redis中查询数据
        String s = stringRedisTemplate.boundValueOps(CacheConstants.IOT_ALL_PRODUCT_LIST).get();
        if (s != null) {
            List<ProductVo> productVos = JSONUtil.toList(s, ProductVo.class);
            return productVos;
        }
        //为空返回集合
        return List.of();
    }

    /**
     * 新增设备
     */

    @Override
    public void registerDevice(DeviceDto deviceDto) {
        //1.判断设备名称是否重入
        LambdaQueryWrapper<Device> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(Device::getDeviceName, deviceDto.getDeviceName());
        Device one = this.getOne(queryWrapper1);
        if (one != null) {
            throw new BaseException("设备不能重复");
        }
        //2.判断设备标识是否重复
        LambdaQueryWrapper<Device> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.eq(Device::getNodeId, deviceDto.getNodeId());
        Device one2 = this.getOne(queryWrapper2);
        if (one2 != null) {
            throw new BaseException("设备标识不能重复");
        }
        //3.判断同一个位置是否有同一种设备
        LambdaQueryWrapper<Device> queryWrapper3 = new LambdaQueryWrapper<>();
        queryWrapper3.eq(Device::getRemark, deviceDto.getRemark());
        queryWrapper3.eq(Device::getProductKey, deviceDto.getProductKey());
        Device one3 = this.getOne(queryWrapper3);
        if (one3 != null) {
            throw new BaseException("不能有同一个设备");
        }
        //1.先从iot里面获取 id
        AddDeviceRequest request = new AddDeviceRequest();
        //获取对象
        AddDevice addDevice = new AddDevice();
        //设备标识
        addDevice.setNodeId(deviceDto.getNodeId());
        addDevice.setDeviceName(deviceDto.getDeviceName());
        //这个就是获取key
        addDevice.setProductId(deviceDto.getProductKey());
        //获取秘钥
        AuthInfo authInfo = new AuthInfo();
        String secret = RandomUtil.randomString(32);
        authInfo.setSecret(secret);
        addDevice.setAuthInfo(authInfo);
        addDevice.setDescription(deviceDto.getDeviceDescription());
        //1.1从body获取
        request.setBody(addDevice);
        AddDeviceResponse addDeviceResponse = client.addDevice(request);
        //2.做判断是否存在
        if (addDeviceResponse.getHttpStatusCode() != 201) {
            throw new BaseException("设备没有注册失败");
        }
        //3.在获取自己表
        //获取设备id就是 iot id
        String deviceId = addDeviceResponse.getDeviceId();
        Device device = new Device();
        device.setIotId(deviceId);
        device.setSecret(secret);
        device.setBindingLocation(deviceDto.getBindingLocation() + "");
        device.setLocationType(deviceDto.getLocationType());
        device.setPhysicalLocationType(deviceDto.getPhysicalLocationType());
        device.setDeviceName(deviceDto.getDeviceName());
        device.setProductKey(deviceDto.getProductKey());
        device.setProductName(deviceDto.getProductName());
        device.setDeviceDescription(deviceDto.getDeviceDescription());
        device.setNodeId(deviceDto.getNodeId());
        device.setRemark(deviceDto.getRemark());
        this.save(device);
    }

    /**
     * 查看设备
     */

    @Override
    public DeviceDetailVo deviceDetail(String iotId) {
        //1.先查看自己的
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getIotId, iotId);
        Device one = this.getOne(queryWrapper);
        if (one == null) {
            throw new BaseException("参数有误");
        }
        //2.获取iot
        DeviceDetailVo deviceDetailVo = BeanUtil.toBean(one, DeviceDetailVo.class);
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse showDeviceResponse = client.showDevice(request);
        if (showDeviceResponse.getHttpStatusCode() != 200) {
            throw new BaseException("iot查询失败");
        }
        deviceDetailVo.setDeviceStatus(showDeviceResponse.getStatus());
        String activeTimeStr = showDeviceResponse.getActiveTime();
        // 把字符串转成LocalDateTime
        LocalDateTime parse = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
        LocalDateTime activeTime = DateTimeZoneConverter.utcToShanghai(parse);
        deviceDetailVo.setActiveTime(activeTime);
        return deviceDetailVo;
    }

    /**
     * 查看设备最新的显示数据
     */
    @Override
    public List<DeviceDataVo> queryServiceProperties(String iotId) {
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse showDeviceShadowResponse = client.showDeviceShadow(request);
        if (showDeviceShadowResponse.getHttpStatusCode() != 200) {
            throw new BaseException("iot查询失败");
        }
        List<DeviceShadowData> shadow = showDeviceShadowResponse.getShadow();
        DeviceShadowData deviceShadowData = shadow.get(0);
        DeviceShadowProperties reported = deviceShadowData.getReported();
        //时间需要转
        String eventTime = reported.getEventTime();
        LocalDateTime parse = LocalDateTimeUtil.parse(eventTime, "yyyyMMdd'T'HHmmss'Z'");
        LocalDateTime actime = DateTimeZoneConverter.utcToShanghai(parse);

        LinkedHashMap<String, Object> linkedHashMap = (LinkedHashMap) reported.getProperties();
        List<DeviceDataVo> list = new ArrayList<>();
        for (String key : linkedHashMap.keySet()) {
            DeviceDataVo deviceDataVo = new DeviceDataVo();
            deviceDataVo.setFunctionId(key);
            deviceDataVo.setEventTime(actime);
            deviceDataVo.setValue(linkedHashMap.get(key));
            list.add(deviceDataVo);
        }

        // 返回集合
        return list;
    }

    /**
     * 修改设备
     */
    @Override
    public String updto(DeviceDto dto) {
        // 先查询设备是否存在
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getNodeId, dto.getNodeId());
        List<Device> devices = this.list(queryWrapper);
        if (devices.isEmpty()) {
            throw new BaseException("设备不存在");
        }
        // 保存查询结果到 one 变量
        Device one = this.getById(dto.getId());

        // 1.1 判断设备名称是否重复
        LambdaQueryWrapper<Device> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(Device::getDeviceName, dto.getDeviceName());
        queryWrapper1.ne(Device::getId, dto.getId());
        Device device = this.getOne(queryWrapper1);
        if (device != null) {
            throw new BaseException("设备名称不能重复");
        }

        int flag = 0;
        // 1.2 判断设备标识是否重复
        if (flag == 0) {
            LambdaQueryWrapper<Device> queryWrapper2 = new LambdaQueryWrapper<>();
            queryWrapper2.eq(Device::getNodeId, dto.getNodeId());
            queryWrapper2.ne(Device::getId, dto.getId());
            device = this.getOne(queryWrapper2);
            if (device != null) {
                throw new BaseException("设备标识不能重复");
            }
        }

        // 1.3 同一位置是否绑定相同产品
        LambdaQueryWrapper<Device> queryWrapper3 = new LambdaQueryWrapper<>();
        queryWrapper3.eq(Device::getLocationType, dto.getLocationType());
        queryWrapper3.eq(Device::getBindingLocation, dto.getBindingLocation());
        queryWrapper3.eq(Device::getProductKey, dto.getProductKey());
        queryWrapper3.ne(Device::getId, dto.getId());
        device = this.getOne(queryWrapper3);
        if (device != null) {
            throw new BaseException("同一位置不能绑定相同产品");
        }

        //2.更新iot设备
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        request.setDeviceId(one.getIotId());
        // 创建更新对象
        UpdateDevice updateDevice = new UpdateDevice();
        updateDevice.setDeviceName(dto.getDeviceName());
        updateDevice.setDescription(dto.getDeviceDescription());
        request.setBody(updateDevice);
        UpdateDeviceResponse updateDeviceResponse = client.updateDevice(request);
        if (updateDeviceResponse.getHttpStatusCode() != 200) {
            throw new BaseException("修改iot失败");
        }
        //3.更新自己的设备
        Device deviceToUpdate = new Device();
        deviceToUpdate.setId(dto.getId());
        deviceToUpdate.setBindingLocation(dto.getBindingLocation() + "");
        deviceToUpdate.setLocationType(dto.getLocationType());
        deviceToUpdate.setPhysicalLocationType(dto.getPhysicalLocationType());
        deviceToUpdate.setDeviceName(dto.getDeviceName());
        deviceToUpdate.setProductKey(dto.getProductKey());
        deviceToUpdate.setProductName(dto.getProductName());
        deviceToUpdate.setDeviceDescription(dto.getDeviceDescription());
        deviceToUpdate.setNodeId(dto.getNodeId());
        deviceToUpdate.setRemark(dto.getRemark());
        this.updateById(deviceToUpdate);
        return "更新成功";
    }

    /**
     * 删除设备
     */

    @Override
    public String delete(String iotId) {
        //1.先删除iot
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.withDeviceId(iotId);
        DeleteDeviceResponse deleteDeviceResponse = client.deleteDevice(request);
        if (deleteDeviceResponse.getHttpStatusCode() != 204) {
            throw new BaseException("设备删除失败");
        }

        //2.删除自己的数据
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getIotId, iotId);
        this.remove(queryWrapper);
        return "删除设备成功";

    }
    /**
     *  报警规则
     */

    @Override
    public AjaxResult queryProduct(String productKey) {
        //获取产品
        ShowProductRequest request = new ShowProductRequest();
        request.setProductId(productKey);
        ShowProductResponse showProductResponse = client.showProduct(request);
        if (showProductResponse.getHttpStatusCode()!=200){
           throw  new BaseException("报警规则错误");
        }
        List<ServiceCapability> serviceCapabilities = showProductResponse.getServiceCapabilities();
        return AjaxResult.success(serviceCapabilities);
    }
}



